<template>
  <basic-container>
    <!-- 表格 -->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="doneTypeList.find((r) => r['key'] === doneType).data"
      :page="page"
      v-model="form"
      :permission="permissionList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="onLoad"
      @on-load="onLoad"
    >
      <!-- 自定义搜索 -->
      <template slot="search">
        <el-form-item
          label="关键字"
          class="el-col-8"
          style="padding-right: 10px"
        >
          <el-input
            placeholder="输入班级、姓名搜索..."
            size="small"
            clearable
            v-model="searchForm.name"
          />
        </el-form-item>
      </template>
      <!-- 左侧 -->
      <template slot="menuLeft">
        <div class="menu-left">
          <!-- 完成状态 -->
          <el-tabs v-model="doneType">
            <el-tab-pane
              v-for="item of doneTypeList"
              :key="item.key"
              :name="item.key"
            >
              <!-- 标题 -->
              <span slot="label">
                {{ item.name }}
                <el-badge :value="item.qty || 0"></el-badge>
              </span>
            </el-tab-pane>
          </el-tabs>
          <div class="menu-left-buttons" v-if="doneType === 'undone'">
            <el-button
              type="warning"
              size="small"
              plain
              icon="el-icon-download"
              @click="handleExport"
              >导出</el-button
            >
          </div>
        </div>
      </template>
      <!-- 自定义操作栏 -->
      <template slot-scope="scope" slot="menu">
        <el-button
          :icon="toHandleIsEdit ? 'el-icon-edit' : 'el-icon-view'"
          :size="scope.size"
          :type="scope.type"
          @click="handleTodo(scope.row)"
        >
          {{ toHandleLabel }}
        </el-button>
      </template>
    </avue-crud>
    <!-- 待办去处理的弹窗 -->
    <HandlePop
      ref="todoHandlePop"
      v-if="showHandlePop"
      :title="`项目名称：${popTitle}`"
      :gradeList="gradeList"
      @close="showHandlePop = false"
      @submitSuccess="onLoad(page, searchForm)"
    />
  </basic-container>
</template>

<script>
import axios from "@/router/axios";
import HandlePop from "./handlePop/index.vue";
import { mapGetters } from "vuex";
import {
  getTodoTotalByType,
  getTodoDetails,
  getColumns,
  getHandlePerm,
  handleExport,
} from "./config.js";
import { getRoleCode } from "@/util/business-util";
import { getTermListAll } from "@/api/system/semester";
import { uniqBy } from "lodash-es";

export default {
  components: { HandlePop },
  props: {
    // 当前用户信息
    curUserInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    // 当前选择的待办类型
    activeNames: {
      type: String,
      default() {
        return "";
      },
    },
  },
  data() {
    return {
      doneType: this.$route.query.doneType === "done" ? "done" : "undone",
      doneTypeList: [
        {
          key: "undone",
          name: "未完成",
          qty: 0,
          data: [], // 数据
        },
        {
          key: "done",
          name: "已完成",
          qty: 0,
          data: [], // 数据
        },
      ],
      toHandleLabel: "",
      toHandleIsEdit: false,
      showHandlePop: false, // 是否显示待办弹窗
      form: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      searchForm: {
        name: this.$route.query.keyword || "",
      },
      routeQuery: {
        gradeName: this.$route.query.gradeName || "",
        yearly: this.$route.query.yearly || "",
        term: this.$route.query.term || "",
        specialTypeId: this.$route.query.specialTypeId || "",
      },
      isNotCallReq: true, // 是否还未做请求加载
      option: {
        height: "auto",
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        selection: false,
        column: [],
      },
      data: [],
      gradeList: [],
      popTitle: "",
      // yearlyList: [],
      // semesterList: [],
      // yearly: "",
      half: "",
      // termId: "",
      query: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.todo_view, false),
      };
    },
    // 当前岗位code
    roleCode() {
      return getRoleCode(this.curUserInfo);
    },
  },
  watch: {
    doneType() {
      this.initOption();
      this.setHandleMenu();
      this.resetPage(); // 重置分页并请求
    },
    roleCode() {
      this.setHandleMenu();
    },
    activeNames() {
      this.setHandleMenu();
    },
  },
  created() {
    this.initGradeList();
    this.initOption(this.routeQuery);
    this.setHandleMenu();
  },
  methods: {
    // 获取年级数据
    async initGradeList() {
      let { data } = await axios({
        url: "/api/blade-system/grade/list",
        method: "get",
        params: {},
      });
      this.gradeList = data.data || [];
    },
    // 初始化option的配置信息
    initOption(params = {}) {
      let columns = getColumns(
        this.curUserInfo,
        this.activeNames,
        this.doneType,
        Object.assign({}, params, this.searchForm)
      );
      this.$set(this.option, "column", columns);
    },
    // 设置操作栏的权限
    setHandleMenu() {
      let obj = getHandlePerm(
        this.curUserInfo,
        this.roleCode,
        this.activeNames,
        this.doneType
      );
      this.option.menu = obj.isShow; // 是否显示操作栏
      this.toHandleIsEdit = obj.isEdit;
      if (obj.isShow) {
        let label = "去处理";
        if (obj.isEdit) {
          if (this.roleCode === "student") {
            label = "去测评";
          }
        } else {
          label = "查看";
        }
        this.toHandleLabel = label;
      }
    },
    resetPage() {
      this.page.currentPage = 1;
      this.page.pageSize = 10;
      this.onLoad(this.page, this.searchForm);
    },
    searchChange(params, done) {
      this.searchForm = Object.assign(
        {},
        { name: this.searchForm.name },
        params
      );
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.searchForm = {};
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 加载数据
    async onLoad(pg, params = {}) {
      params = this.getParams(params);
      this.loading = true;
      this.refreshTotal(params); // 刷新已完成/未完成数量
      // 查询待办详情
      getTodoDetails(
        this.curUserInfo,
        this.activeNames,
        Object.assign({}, this.query, params),
        this.doneType,
        pg || this.page
      )
        .then((data) => {
          this.isNotCallReq = false;
          this.page.total = (data && data.total) || 0;
          let statusObj = this.doneTypeList.find(
            (r) => r["key"] === this.doneType
          );
          this.$set(statusObj, "data", (data && data.data) || []);
          console.log(data);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取参数
    getParams(params) {
      //判断是否直接展示专项测试
      if (this.$route.query.specialTypeId) {
        params.specialTypeId = 1;
      }
      let tenantId = JSON.parse(window.localStorage.getItem("saber-userInfo"))
        .content.tenantId;
      this.query = {
        tenantId: this.$route.query.tenantId || tenantId,
      };
      // 判断是否还未请求
      if (this.isNotCallReq) {
        params = Object.assign({}, params, this.routeQuery);
        this.searchForm = Object.assign(
          {},
          { name: this.searchForm.name },
          this.routeQuery
        );
      }
      params = Object.assign({}, params, this.searchForm);
      return params;
    },
    // 刷新已完成/未完成数量
    refreshTotal(params) {
      // 根据类型获取已完成/未完成的数量
      getTodoTotalByType(
        this.activeNames,
        this.curUserInfo,
        Object.assign({}, this.query, params)
      ).then((obj) => {
        let undoneObj = this.doneTypeList.find((r) => r["key"] === "undone");
        let doneObj = this.doneTypeList.find((r) => r["key"] === "done");
        this.$set(undoneObj, "qty", obj["undoneQty"]);
        this.$set(doneObj, "qty", obj["doneQty"]);
      });
    },
    // 去处理
    handleTodo(rowData) {
      // 测评
      if (this.activeNames === "evaluation") {
        // 去测评
        if (this.toHandleIsEdit) {
          this.$router.push({
            name: "心理测评详情",
            query: {
              projectGaugeTypeId: rowData.gaugeTypeId,
              projectId: rowData.projectId,
            },
          });
        }
        // 查看测试报告
        else {
          this.$router.push({
            name: "个人档案",
            query: {
              userId: rowData.userId || rowData.includeId,
            },
          });
        }
      } else {
        this.showHandlePop = true;
        this.popTitle = rowData.projectName || "";
        this.$nextTick(() => {
          this.$refs["todoHandlePop"].show(
            this.activeNames,
            rowData,
            this.doneType === "undone"
          );
        });
      }
    },
    // 导出
    handleExport() {
      let params = this.getParams(Object.assign({}, this.searchForm));
      // 导出
      handleExport(
        this.curUserInfo,
        this.activeNames,
        params,
        this.doneType,
        this.page
      );
    },
  },
};
</script>

<style scoped lang="scss">
.menu-left {
  display: flex;
  justify-content: space-between;
  .menu-left-buttons {
    margin-left: 40px;
    .el-button--small {
      position: relative;
      top: 7px;
    }
  }
}
</style>
